import sys

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

styleSheet = \
"""
QPushButton{
    height: 10px;
    width: 10px;
    border-style: none;
    border-radius: 5px;
    background-color: #DDD;
}
QPushButton:hover{
    background-color: #CCC;
}
"""

class SwiperWidget(QWidget):
    currentIdx = 0
    pages = 0
    imageLabel = []
    switchBtn = []
    currentStyle = "background-color: #B0B0B0;"

    def __init__(self, parent=None):
        super().__init__(parent)
        vLayout = QVBoxLayout()
        self.setLayout(vLayout)

        self.imageStack = QStackedWidget()  # 用来存放展示图片的Label的StackedWidget
        vLayout.addWidget(self.imageStack)
        self.hLayout = QHBoxLayout()  # 用来布置底部圆形按钮的水平布局
        self.hLayout.setSpacing(10)
        self.hLayout.addStretch(1)
        self.hLayout.addStretch(1)
        vLayout.addItem(self.hLayout)
        self.setStyleSheet(styleSheet)  # 设置样式表
        self.timer = QTimer()  # 用于自动翻页的定时器
        self.timer.timeout.connect(self.autoChangePage)

    # 添加图片页
    def addPage(self, imgPath=None):
        newLabel = QLabel(self, text=("图片" + str(self.pages)))
        newLabel.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
        self.imageLabel.append(newLabel)
        self.switchBtn.append(QPushButton(self, objectName=str(self.pages), clicked=self.changePage))
        self.imageStack.addWidget(newLabel)
        if imgPath:
            img = QPixmap(imgPath)
            img = img.scaled(399, 344, Qt.KeepAspectRatio)  # 调整图片尺寸，保持长宽比
            newLabel.setPixmap(img)
        self.hLayout.insertWidget(self.pages + 1, self.switchBtn[self.pages])
        if self.pages == 0:
            self.switchBtn[0].setStyleSheet(self.currentStyle)
            self.timer.start(6000)
        self.pages += 1
        return self.pages  # 返回控件数量

    # 点击按钮，图片切换
    def changePage(self):
        sender = self.sender()
        print("按下了按钮" + sender.objectName())
        self.switchBtn[self.currentIdx].setStyleSheet("")
        sender.setStyleSheet(self.currentStyle)
        self.currentIdx = int(sender.objectName())
        self.imageStack.setCurrentIndex(self.currentIdx)
        self.timer.start(6000)

    # 定时器自动换页
    def autoChangePage(self):
        self.switchBtn[self.currentIdx].setStyleSheet("")
        self.currentIdx = (self.currentIdx + 1) % self.pages
        self.switchBtn[self.currentIdx].setStyleSheet(self.currentStyle)
        self.imageStack.setCurrentIndex(self.currentIdx)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = SwiperWidget()
    widget.addPage()
    widget.addPage()
    widget.addPage()
    widget.show()
    sys.exit(app.exec_())